import 'dart:convert';

import 'package:FiduMart/app_routes.dart';
import 'package:FiduMart/constants/constants.dart';
import 'package:FiduMart/core/network/model/association_entity.dart';
import 'package:FiduMart/core/utils/image_constant.dart';
import 'package:FiduMart/core/utils/pref_utils.dart';
import 'package:FiduMart/screen/webview/web_controller.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:FiduMart/core/network/RequestClientMark.dart';
import 'package:FiduMart/core/network/model/base/base_model_entity.dart';
import 'package:FiduMart/core/network/model/currencyrank_list_entity.dart';
import 'package:FiduMart/core/utils/common_util.dart';
import 'package:FiduMart/core/utils/logger.dart';
class QuotesController extends GetxController {


  var clubPage = 1;

  var investList = <CurrencyrankListList>[].obs;

  var sort = "default".obs;


  var currencyrankItemCun = CurrencyrankListList().obs ;

  // var associationEntity = AssociationEntity().obs ;

  final inputController = TextEditingController();
  var queryString = "".obs;
  var associationProjectList = <AssociationProject>[].obs;

  @override
  void onInit() {
    super.onInit();
    httpOnRefresh();
  }


  /****
   * 刷新逻辑
   */
  Future<void> httpOnRefresh() async {
    clubPage = 1;
    getMiningInvestList(
        page:1
    );
  }


  /***
   * 加载逻辑
   */
  void httpOnLoad(){
    clubPage = clubPage + 1;
    getMiningInvestList(
        page:clubPage
    );
  }

  Future getMiningInvestList({
    int? page, // 页码，默认为1
    int? pageSize = 100, // 每页大小，默认为10
  }) async {
    try {
      var apiName = "/ticker/currencyranklist";

      // 获取当前时间
      DateTime now = DateTime.now();
      // 将当前时间转换为毫秒级时间戳
      int timestamp = now.millisecondsSinceEpoch;


      if(sort=="desc"){
        var response = await RequestClientMark().get(apiName, {
          "pages":page,
          "sizes":pageSize,
          "subject":'market_cap',
          "language":'locale'.tr,
          "timestamp":timestamp.toString(),
          "code":CommonUtil.getEncryptCode(timestamp.toString()),
          "platform":'web_pc',
          "v":'0.1.0',
          "legal_currency":'USD',
          "international":1,
          "sort":'percent_change_24h',
          "direction":'desc', //desc
        });

        var responseEntity =
        BaseModelEntity<CurrencyrankListEntity>.fromJson(response);
        return setListInvestData(page, responseEntity, pageSize );
      }else if(sort=="asc"){
        var response = await RequestClientMark().get(apiName, {
          "pages":page,
          "sizes":pageSize,
          "subject":'market_cap',
          "language":'locale'.tr,
          "timestamp":timestamp.toString(),
          "code":CommonUtil.getEncryptCode(timestamp.toString()),
          "platform":'web_pc',
          "v":'0.1.0',
          "legal_currency":'USD',
          "international":1,
          "sort":'percent_change_24h',
          "direction":'asc', //desc
        });

        var responseEntity =
        BaseModelEntity<CurrencyrankListEntity>.fromJson(response);
        return setListInvestData(page, responseEntity, pageSize );
      }else{
        var response = await RequestClientMark().get(apiName, {
          "pages":page,
          "sizes":pageSize,
          "subject":'market_cap',
          "language":'locale'.tr,
          "timestamp":timestamp.toString(),
          "code":CommonUtil.getEncryptCode(timestamp.toString()),
          "platform":'web_pc',
          "v":'0.1.0',
          "legal_currency":'USD',
          "international":1
        });

        var responseEntity =
        BaseModelEntity<CurrencyrankListEntity>.fromJson(response);
        return setListInvestData(page, responseEntity, pageSize );

      }

/*      var response = await RequestClientMark().get(apiName, {
        "pages":page,
        "sizes":pageSize,
        "subject":'market_cap',
        "language":'locale'.tr,
        "timestamp":timestamp.toString(),
        "code":CommonUtil.getEncryptCode(timestamp.toString()),
        "platform":'web_pc',
        "v":'0.1.0',
        "legal_currency":'USD',
        "international":1,
        "sort":'percent_change_24h',
        "direction":'asc', //desc

        //sort: percent_change_24h
        // direction: asc
      });*/
    } catch (error) {
      print("Error: $error");
      throw error;
    }
  }

  void setListInvestData(int? page, BaseModelEntity<CurrencyrankListEntity> responseEntity, int? pageSize) {
    if (page == 1) {
      investList.clear();
    } if (responseEntity.data != null && responseEntity.data!.list != null) {
      investList.addAll(responseEntity.data!.list!);
    }
    Logger.log("data-setListInvestData:${investList.length}");
  }

  String titleDoubleJudgingGSH(String numberString) {
    double numberDouble = double.parse(numberString); // 转换为double类型
    String formattedNumber = numberDouble.toStringAsFixed(2); // 格式化为字符串并保留两位小数
    double roundedNumber = double.parse(formattedNumber);
    return roundedNumber.toString();
  }


  String toDoubleJudgingyiUstd(String numberString) {
    double numberDouble = double.parse(numberString); // 转换为double类型
    String formattedNumber = NumberFormat.compactCurrency(
      decimalDigits: 2,
      symbol: '',
    ).format(numberDouble / 100000000); // 将数值除以1亿
    return formattedNumber.toString();
  }


  Future getcurrencyKline({
    required CurrencyrankListList currencyrankItem,
    required String period,
  }) async {
    try {

      currencyrankItemCun.value = currencyrankItem;

      final pref = Get.find<PrefUtils>();

      var langStr = await pref.getLang();
      Map<String, String> actLangMap = {
        'en_US': 'en',
        'ru_RU': 'ru',
        'th_TH': 'tha',
        'zh_CN': 'zh',
      };
      var langStrh5 = actLangMap[langStr] ?? 'en';

      Logger.log("langStrh5:${langStrh5}");

/*      Get.toNamed(AppRoutes.webviewScreen, parameters: {
        "url": kReleaseMode?"https://www.vvbit.io/?lang=$langStrh5":"http://192.168.2.34:5173?lang=$langStrh5",
        "title": "mark_details".tr,
        "data":jsonEncode(currencyrankItemCun.value.toJson())
      });*/

      Get.toNamed(AppRoutes.webviewScreen, parameters: {
        "url": getMarkH5KLine().toString()+langStrh5,
        "title": "mark_details".tr,
        "data":jsonEncode(currencyrankItemCun.value.toJson())
      });

    } catch (error) {
      print("Error: $error");
      throw error;
    }
  }

  void currencyranklistSort() {
    //  "direction":'asc', //desc
    if(sort=="default"){
      sort.value = 'asc';
    }else if(sort=="asc"){
      sort.value = 'desc';
    }else{
      sort.value = 'default';
    }
    httpOnRefresh();
  }

  String exchangeBuyStateTP(){
    var exchangetr = '';
    if(sort=="default"){
      exchangetr = ImageConstant.icon_rise_default;
    }else if(sort=="asc"){
      exchangetr = ImageConstant.icon_rise_up;
    }else if(sort=="desc"){
      exchangetr = ImageConstant.icon_rise_down;
    }else{
      exchangetr = ImageConstant.icon_rise_up;
    }
    return exchangetr;
  }

  void h5GetcurrencyKline(String period){
    getcurrencyKline(
      currencyrankItem:currencyrankItemCun.value,
      period: period,

    );
  }


  void currencySearch(){
    getCurrencyHistoryprice(queryString:queryString.value);
  }

  Future getCurrencyHistoryprice({
    required String queryString,
  }) async {
    try {
      var apiName = "/esearch/association";
      // 获取当前时间
      DateTime now = DateTime.now();
      // 将当前时间转换为毫秒级时间戳
      int timestamp = now.millisecondsSinceEpoch;


      var response = await RequestClientMark().get(apiName, {
        "queryString":queryString.toString(),
        "timestamp":timestamp.toString(),
        "category":"project",
        "code":CommonUtil.getEncryptCode(timestamp.toString()),
        "platform":'web_pc',
        "v":'0.1.0',
        "language":'locale'.tr,
        "legal_currency":'USD'
      });

/*      associationEntity.value =
      BaseModelEntity<AssociationEntity>.fromJson(response).data!;*/

      var responseEntity =
      BaseModelEntity<AssociationEntity>.fromJson(response);
      return setListCurrencySearch(responseEntity);

    } catch (error) {
      print("Error: $error");
      throw error;
    }
  }


  void setListCurrencySearch(BaseModelEntity<AssociationEntity> responseEntity) {
    associationProjectList.clear();
    if (responseEntity.data != null && responseEntity.data!.project != null) {
      associationProjectList.addAll(responseEntity.data!.project!);
    }
    Logger.log("data-setListInvestData:${investList.length}");
  }


  void currencySearchClear(){
    inputController.text = '';
    associationProjectList.clear();
  }

  Future getCurrencyrankItem({
    required AssociationProject associationProject,
  }) async {
    try {

      final pref = Get.find<PrefUtils>();

      var langStr = await pref.getLang();
      Map<String, String> actLangMap = {
        'en_US': 'en',
        'ru_RU': 'ru',
        'th_TH': 'tha',
        'zh_CN': 'zh',
      };
      var langStrh5 = actLangMap[langStr] ?? 'en';

      Logger.log("langStrh5:${langStrh5}");

      Get.toNamed(AppRoutes.webviewScreen, parameters: {
        "url": getMarkH5KLine().toString()+langStrh5,
        "title": "mark_details".tr,
        "assocdata":jsonEncode(associationProject.toJson())
      });

    } catch (error) {
      print("Error: $error");
      throw error;
    }
  }


}

